﻿using AutoMapper;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SqlSugar;
using System.Security.Claims;
using Zhao.Arena.Utility.InitDatabaseExt;
using Zhao.Common.Helper;
using Zhao.IServer.menu;
using Zhao.Models.DTO;
using Zhao.Models.Entity;

namespace Zhao.Arena.Controllers.menu
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class MenusController : ControllerBase
    {
        private readonly IMenusServer _menusServer;
        private readonly IMapper _IMapper;

        public MenusController(IMenusServer menusServer, IMapper IMapper)
        {
            this._menusServer = menusServer;
            this._IMapper = IMapper;
        }

        /// <summary>
        /// 菜单树分页列表
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pageSize"></param>
        /// <param name="searchaString"></param>
        /// <returns></returns>
        [HttpGet()]
        [Route("{pageindex:int}/{pageSize:int}/{searchaString}")]
        [Route("{pageindex:int}/{pageSize:int}")]
        public async Task<JsonResult> GetMenuPageAsync(int pageindex = 1, int pageSize = 10, string? searchaString = null)
        {
            var pageModel = await _menusServer.GetMenuTreePageAsync(pageindex, pageSize, searchaString);

            var data = _IMapper.Map<PageModel<Menus>, PageModel<MenuDTO>>(pageModel);

            var result = new JsonResult(new ApiResult<PageModel<MenuDTO>>()
            {
                Data = data,
                Success = true,
                Message = "获取分页菜单"
            });
            return result;
        }


        /// <summary>
        /// 获取所有的菜单信息--为树形下拉列表使用 
        /// 如果传递menuId就是编辑 就不能展示当前自身(避免选择父级的时候选择到自身 然后引发菜单错误)
        /// </summary>
        /// <param name="menuId"></param>
        /// <returns></returns>
        [HttpGet()]
        [Route("GetMenusTreeSelectList")]
        [Route("GetMenusTreeSelectList/{menuId}")]
        public async Task<JsonResult> GetMenusTreeSelectList(Guid? menuId)
        {
            var menusTreeList = await _menusServer.GetMenuTreeAsync(menuId == null ? default : menuId.Value);
            var datalist = _IMapper.Map<List<Menus>, List<TreeSelectDTO>>(menusTreeList);
            datalist.Insert(0, new TreeSelectDTO()
            {
                Label = "----作为顶级菜单------",
                Value = "00000000-0000-0000-0000-000000000000",
                Selected = true
            });
            var result = new JsonResult(new ApiResult<List<TreeSelectDTO>>()
            {
                Data = datalist,
                Success = true,
                Message = "获取所有的菜单信息"
            });
            return result;
        }


        /// <summary>
        /// 验证菜单是否存在
        /// </summary>
        /// <param name="menuid"></param>
        /// <param name="keywords"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("ValidateMenu/{menuid}/{keywords}")]
        public async Task<JsonResult> ValidateMenu(Guid menuid, string keywords)
        {
            Expressionable<Menus> expressionable = new Expressionable<Menus>();
            expressionable.And(m => m.WebUrlName.Equals(keywords) && !m.Id.Equals(menuid));
            if (_menusServer.Query(expressionable.ToExpression()) != null)
            {
                return await Task.FromResult(new JsonResult(new ApiResult()
                {
                    Success = false,
                    Message = "已存在"
                }));
            }
            else
            {
                return new JsonResult(new ApiResult()
                {
                    Success = true,
                    Message = "验证成功"
                });
            }
        }


        /// <summary>
        /// 新增菜单
        /// </summary>
        /// <param name="menuDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> AddMenuAsync(MenuDTO menuDto)
        {
            ApiResult apiResult = await _menusServer.AddOrUpdateMenuAsync(menuDto);
            return new JsonResult(apiResult);
        }

        /// <summary>
        /// 根据Id获取一条信息
        /// </summary>
        /// <param name="menuId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetMenuById")]
        [Route("GetMenuById/{menuId}")]
        public async Task<JsonResult> GetMenuById(Guid menuId)
        {
            ApiResult<MenuDTO> result = new ApiResult<MenuDTO>
            {
                Success = false,
                Message = "未查询到数据"
            };
            var menus = await _menusServer.QueryAsync(x => x.Id == menuId);

            result.Data = _IMapper.Map<Menus, MenuDTO>(menus);

            if (result.Data != null)
            {
                result.Success = true;
                result.Message = "查询成功";
            }

            return new JsonResult(result);
        }


        /// <summary>
        /// 修改菜单
        /// </summary>
        /// <param name="menuDto"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<JsonResult> UpdMenuAsync(MenuDTO menuDto)
        {
            ApiResult apiResult = await _menusServer.AddOrUpdateMenuAsync(menuDto);
            return new JsonResult(apiResult);
        }


        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="menuId"></param>
        /// <returns></returns>
        [HttpDelete]
        [Route("{menuId}")]
        public async Task<JsonResult> DelMenuAsync(Guid menuId)
        {
            ApiResult result = new ApiResult
            {
                Success = false,
                Message = "操作失败"
            };

            if (await _menusServer.DelMenuAsync(menuId))
            {
                result.Success = true;
                result.Message = "操作成功";
            }

            return new JsonResult(result);
        }


        /// <summary>
        ///【获取菜单列表-根据某一个用户来计算得到归属于这个用户的权限数据---菜单】
        /// </summary>
        /// <returns>返回带有树形结果的菜单列表</returns> 
        [HttpGet()]
        [Route("MenuTree")]
        public async Task<JsonResult> GetMenuTreeListAsync()
        {

            string? idClaim = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Role))?.Value;

            Int32.TryParse(idClaim, out int id);

            if (id == default) return new JsonResult(new ApiResult
            {
                Message = "当前没有权限",
                Success = false
            });

            var menusTreeList = await _menusServer.GetMenusTreeList(id);
            var result = new JsonResult(new ApiResult<List<MenuDTO>>()
            {
                Data = _IMapper.Map<List<Menus>, List<MenuDTO>>(menusTreeList),
                Success = true,
                Message = "获取菜单列表"
            });
            return await Task.FromResult(result);
        }
    }
}
